package com.tange.module.core.wifi.scan;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.appbase.custom.BuildConfig;
import com.tange.base.toolkit.GlobalApplicationContext;
import com.tange.base.toolkit.NetworkUtil;
import com.tange.base.toolkit.PhoneUtils;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.WifiAp;
import com.tg.appcommon.android.TGLog;

public class BizWiFiUtil {

    private static final String TAG = "BizWiFiUtil";

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void addCameraWifi(String uuid) {
        String brand = Build.BRAND;//手机厂商
        if (!TextUtils.equals(brand.toLowerCase(), "redmi") && !TextUtils.equals(brand.toLowerCase(), "xiaomi")) {
            WifiAp wifiAp = NetworkUtil.getConnectWifiSSID(GlobalApplicationContext.application());
            String wifi = getDeviceWifi(uuid);
            TGLog.i(TAG, "addCameraWifi wifi = " + wifi + ", wifiAp.ssid = " + wifiAp.ssid);
            if (!wifi.equals(wifiAp.ssid)) {
                TGLog.i(TAG, "addCameraWifi == wifi = " + wifi + ", wifiAp.ssid = " + wifiAp.ssid);
                WiFiScanManager.scanner().addCameraWifi(wifi, GlobalApplicationContext.application());
            }else {
                WiFiScanManager.scanner().setCameraUseWifiData(GlobalApplicationContext.application());
            }
        }
    }

    public static String getDeviceWifi(@NonNull String uuid) {
        return DeviceAccessPointNameStitching.INSTANCE.parse(uuid);
    }

    public static void removeDeviceNetwork(Context context, String wifi) {
        if (context == null) return;
        if (!StringUtils.isEmpty(wifi) && wifi.startsWith(ApScanConfiguration.INSTANCE.apNamePrefixEndsWithUnderLine())) {
            WiFiScanManager.scanner().removeNetwork(context, wifi);
            //连接一个未知的wifi来切网络
            if (!PhoneUtils.isMi()){
                WiFiScanManager.scanner().addCameraWifi("Wi_FI",GlobalApplicationContext.application());
            }
            WiFiScanManager.scanner().resetDeviceNetWork(context);
        }
    }

    public static void removeDeviceWifi() {
        String wifi = WifiToolkit.getCurWifi();
        TGLog.d(TAG,  "wifi = " + wifi + "tempConfig == null");
        removeDeviceNetwork(GlobalApplicationContext.application(), wifi);
    }

    public static void saveNetworkWifi() {
        String wifi = WifiToolkit.getCurWifi();
        TGLog.d(TAG,  "savewifi = " + wifi);
        WiFiScanManager.scanner().getNetworkCapabilities(GlobalApplicationContext.application());
        if (!StringUtils.isEmpty(wifi) && !wifi.startsWith(ApScanConfiguration.INSTANCE.apNamePrefixEndsWithUnderLine())) {
            PreferenceUtil.setString(GlobalApplicationContext.application(), WifiToolkit.TG_WIFI_NAME, wifi);
        }
    }

}
